//
//  MyPeerListViewController.m
//  安好
//
//  Created by lianchuang on 14/12/8.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "MyPeerListViewController.h"
#import "AppDelegate.h"
#import "PeerList.h"
#import "MyPeerlistViewCell.h"
#import "FirendDetailViewController.h"
#import "ChatContent.h"
#import "PeerList.h"
#import "ConsultList.h"
#import "YXJSON.h"
#import "ConsultingChatViewController.h"
#import "MyFriendViewController.h"
#import "FMDatabaseQueue.h"
#import "SystemMessageCenter.h"
#import "LCStatusBarOverlay.h"
#import "NoPeerListview.h"
@interface MyPeerListViewController ()<ChatDelegate>

@end

@implementation MyPeerListViewController
{
    UILabel *labelBG;
    NoPeerListview *noPeer;
}
-(void)viewWillAppear:(BOOL)animated
{
    [self app];
    self.dataArray=[PeerList readAllPeerListItem];
    if (self.dataArray.count<=0) {
        self.tableview.hidden=YES;
    }
    else
    {
        noPeer.hidden=YES;
    }
    [self.tableview reloadData];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [[LCStatusBarOverlay shared] hidenMessageLabel];
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.chatDelegate=nil;
}
- (void)inntLabelCenter
{
//    labelBG=[[UILabel alloc] initWithFrame:CGRectMake((kScreenWidth-200)/2, kScreenHeight/2-64, 200, 21)];
//    labelBG.text=@"暂无对话";
//    labelBG.textColor=TITLE_ARTICLE_CONTENTFONT_COLOR;
//    labelBG.textAlignment=NSTextAlignmentCenter;
//    labelBG.font=[UIFont systemFontOfSize:15];
//    [self.view addSubview:labelBG];
    if (IPhone6Plus) {
        noPeer=[[[NSBundle mainBundle]loadNibNamed:@"NoPeerListview" owner:self options:nil] lastObject];

    }else
    {
        noPeer=[[[NSBundle mainBundle]loadNibNamed:@"NoPeerListview" owner:self options:nil] firstObject];

    }
    CGPoint point=CGPointMake(kScreenWidth/2, kScreenHeight/2-64);
    [self.view addSubview:noPeer];
    noPeer.center=point;


}
- (AppDelegate *)app
{
    AppDelegate *app=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    app.chatDelegate=self;
    return app;
}
- (void)receiveMessage:(AppDelegate *)appD Message:(id)message
{
//    NSLog(@"%@",message);
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    //判断同行or非同行 。type=1同行；type=2医患关系。
    //    PeerList *peerList=[[PeerList alloc]initWithDictionary:dict];
    NSString *readStatus;
    if ([[dict objectForKey:@"type"] intValue] == 1) {
        if ([ConsultList isExistItem:dict AndDb:[MyFMDB openDB]]) {
            readStatus=@"1";
        }else
        {
            readStatus=@"1";
        }
        
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            
            
            //加入耗时操作
            NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
            CGSize size;
            if ([[messageDic valueForKey:@"pic"]length]>0) {
                size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
            }
            else{
                [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
            }

            if ([PeerList updatePeerList:message withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                self.dataArray= [PeerList readAllPeerListItem];
                if (self.dataArray.count>0) {
                    noPeer.hidden=YES;
                    self.tableview.hidden=NO;
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
                [self.tableview reloadData];
            }
            
        });
    }else
    {
        readStatus=@"1";
        dispatch_queue_t queue = dispatch_get_main_queue();
        dispatch_async(queue, ^{
            
            
            
            
            //加入耗时操作
            NSDictionary *messageDic=[YXJSON dictionaryOrArrayWithJSONSString:message];
            CGSize size;
            
            [ConsultList updateConsultList:message withReadStatus:readStatus withSuccess:@"1"withMessageDirection:@"2"];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
            NSString *meth=[NSString stringWithFormat:@"%@",[dict valueForKey:@"method"]];
            if ([meth isEqualToString:@"9"]) {
                return;
            }
            if ([[messageDic valueForKey:@"pic"]length]>0) {
                size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
            }
            else{
                [ChatContent insertChatMessageItem:message Andsuccess:@"1" AndMessageDirection:@"2"];
            }
        });
    }
    
}
- (void)receiveRemoteNotificationMessage:(AppDelegate *)appD Message:(id)message
{
    NSDictionary *dict = [YXJSON dictionaryOrArrayWithJSONSString:message];
    //遍历消息内容数组，排序后将消息插入数据库（如果和当前用户是同一人，并展示聊天消息）
    
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *sqlPath=[docPath stringByAppendingPathComponent:@"mydatabase.sqlite"];
    FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:sqlPath];
    dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
    //    dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
    dispatch_async(q1, ^{
        
        NSArray * array1 = [[[dict objectForKey:@"history"] allKeys]sortedArrayUsingSelector:@selector(compare:)];
        for (int index=0; index<array1.count; index++) {
            NSString *keys=[array1 objectAtIndex:index];
            if([[[[dict objectForKey:@"history"] objectForKey:keys] objectForKey:@"action"] isEqualToString:@"send"])
            {
                //在其他界面收到聊天消息，只进行存取数据（2个表）
                NSMutableDictionary *MutDic=[NSMutableDictionary dictionaryWithDictionary:[[dict objectForKey:@"history"] objectForKey:keys]];
                [MutDic setValue:@"2" forKey:@"messageDirection"];
                NSString *messageType;
                if ([[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"message"] length] > 0) {
                    messageType = @"1";
                } else if ([[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"pic"] length] > 0) {
                    messageType = @"2";
                } else {
                    messageType = @"3";
                }
                [MutDic setValue:messageType forKey:@"messageType"];
                //判断同行or非同行 。type=1同行；type=2医患关系。
                //            ConsultList *consultList=[[ConsultList alloc]initWithDictionary:MutDic];
                NSString *readStatus;
                if ([[[[dict objectForKey:@"history"] objectForKey:keys]  objectForKey:@"type"] intValue] == 1) {
                    if ([ConsultList isExistItem:dict AndDb:[MyFMDB openDB]]) {
                        readStatus=@"1";
                    }else
                    {
                        readStatus=@"1";
                    }
                    //加入耗时操作
                    NSDictionary *messageDic=[[dict objectForKey:@"history"] objectForKey:keys];
                    CGSize size;
                    if ([[messageDic valueForKey:@"pic"]length]>0) {
                        size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                        
                        [queue inDatabase:^(FMDatabase *db) {
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                            if ([PeerList updatePeerList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                            }
                        }];
                        
                    }
                    else
                    {
                        [queue inDatabase:^(FMDatabase *db) {
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] Andsuccess:@"1" AndMessageDirection:@"2"];
                            
                            if ([PeerList updatePeerList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                            }
                        }];
                    }

                }else
                {
                    readStatus=@"1";
                    
                    //加入耗时操作
                    NSDictionary *messageDic=[[dict objectForKey:@"history"] objectForKey:keys];
                    CGSize size;
                    if ([[messageDic valueForKey:@"pic"]length]>0) {
                        size=[ChatContent downloadImageSizeWithURL:[messageDic valueForKey:@"pic"]];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.width] forKey:@"width"];
                        [messageDic setValue:[NSString stringWithFormat:@"%f",size.height] forKey:@"heigth"];
                        
                        [queue inDatabase:^(FMDatabase *db) {
                            [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:messageDic] Andsuccess:@"1" AndMessageDirection:@"2"];
                            if ([ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                            }
                        }];
                        
                    }
                    else{
                        [queue inDatabase:^(FMDatabase *db) {
                            
                            if ([ConsultList updateConsultList:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] withReadStatus:readStatus withSuccess:@"1" withMessageDirection:@"2"]) {
                                NSString *meth=[NSString stringWithFormat:@"%@",[[[dict objectForKey:@"history"] objectForKey:keys] valueForKey:@"method"]];
                                if ([meth isEqualToString:@"9"]) {
                                    return;
                                }
                                [ChatContent insertChatMessageItem:[YXJSON JSONStringWithDictionaryOrArray:[[dict objectForKey:@"history"] objectForKey:keys]] Andsuccess:@"1" AndMessageDirection:@"2"];
                            }

                        }];
                    }
                }
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.dataArray=[PeerList readAllPeerListItem];
            if (self.dataArray.count>0) {
                noPeer.hidden=YES;
                self.tableview.hidden=NO;
            }
            [self.tableview reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];

        });
    });
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [[NSMutableArray alloc] init];
    self.tableview.dataSource=self;
    self.tableview.delegate=self;
    [self setNaviBarAttribute];
    self.navigationItem.title = @"对话列表";
    [self.tableview setBackgroundColor:[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16]];
    self.view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    if (kScreenHeight==480) {
        self.tableview.frame=CGRectMake(0, 0, kScreenWidth,CGRectGetHeight(self.view.frame));
    }else
    {
        self.tableview.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }
    [self inntLabelCenter];

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier=@"cell";
    MyPeerlistViewCell *cell=[tableView dequeueReusableCellWithIdentifier:indentifier];
    if (!cell) {
        if (kScreenWidth==414) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"MyPeerlistViewCell" owner:self options:nil] lastObject];

        }else{
            cell=[[[NSBundle mainBundle]loadNibNamed:@"MyPeerlistViewCell" owner:self options:nil] objectAtIndex:0];
        }
    }
    PeerList *peerList=[self.dataArray objectAtIndex:indexPath.row];
    
    MyNSLog(" wwwwww   %@",[NSString stringWithFormat:@"%@%@&size=big%@",BaseMessageListIconHeadUrl,peerList.uid,BaseMessageListIconTailUrl]);
    
    [cell.userImage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@&size=big%@",BaseMessageListIconHeadUrl,peerList.uid,BaseMessageListIconTailUrl]] placeholderImage:[UIImage imageNamed:@"默认头像"]options:SDWebImageRefreshCached];
    cell.userImage.layer.cornerRadius=3;
    cell.userImage.layer.masksToBounds=YES;
    cell.userName.text=peerList.username;
    cell.userSignature.text=peerList.message;
    NSDate *nowDate = [NSDate date];
    int seconds ;
    NSString *tim1=[NSString stringWithFormat:@"%f",[peerList.dateline doubleValue]];
    if (tim1.length>19) {
        seconds=  nowDate.timeIntervalSince1970 - [peerList.dateline doubleValue]/10000;
    }else
    {
        seconds=  nowDate.timeIntervalSince1970 - [peerList.dateline doubleValue];
    }
    if(seconds < 60) {
        cell.dateline.text = @"刚刚";
    } else if(seconds < 60*60) {
        cell.dateline.text = [NSString stringWithFormat:@"%d分钟前", seconds/60%60];
    } else if(seconds < 24*60*60) {
        cell.dateline.text = [NSString stringWithFormat:@"%d小时前", seconds/60/60%24];
    } else if(seconds < 4*24*60*60) {
        cell.dateline.text = [NSString stringWithFormat:@"%d天前", seconds/60/60/24%4];
    } else {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
        NSString *tim1=[NSString stringWithFormat:@"%f",[peerList.dateline doubleValue]];
        if (tim1.length>19) {
            tim1=[NSString stringWithFormat:@"%f",[peerList.dateline doubleValue]/10000];
        }else
        {
            tim1=peerList.dateline;
        }
        NSString *dateString = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:tim1.integerValue]];
        cell.dateline.text = dateString;
    }
    if ([peerList.noread isEqualToString:@"1"]) {
        cell.answer.hidden=NO;
    }else
    {
        cell.answer.hidden=YES;
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(kScreenWidth==414)
    {
        return  82;
    }
    return 65;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    PeerList *peer=[self.dataArray objectAtIndex:indexPath.row];
    if ([peer.noread isEqual:@"1"]) {
        [PeerList resetUnreadCountWithUid:peer.uid];
    }
    ConsultingChatViewController * consultingViewController = [[ConsultingChatViewController alloc]init];
    consultingViewController.userName = peer.username;
    NSString * docid = peer.uid;
    if ([docid length] <= 0) {
        consultingViewController.touid = peer.uid;
    }else{
        consultingViewController.touid = docid;
    }
    consultingViewController.toTpye = @"1";
    consultingViewController.toMed = @"0";
    consultingViewController.qid=@"0";
    consultingViewController.isFromwhere=0;
    [self.navigationController pushViewController:consultingViewController animated:YES];

}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        PeerList *peerList=[self.dataArray objectAtIndex:indexPath.row];
        [self.dataArray removeObject:peerList];
        [PeerList deleteConsultListWithUid:peerList.uid];
        if ([peerList.noread isEqualToString:@"1"]) {
            LCStatusBarOverlay *statusBar=[LCStatusBarOverlay shared];
            NSString *uid=[NSString stringWithFormat:@"%@",[statusBar.dic valueForKey:@"uid"]];
            if ([uid isEqualToString:peerList.uid]) {
                [statusBar hidenMessageLabel];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:kDidGetAndStoreSystemNotification object:nil];
        }
        
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        if (self.dataArray.count<=0) {
            noPeer.hidden=NO;
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    UIButton *right=[UIButton buttonWithType:UIButtonTypeCustom];
    right.frame = CGRectMake(0, 0, 50, 30);
//    [right setImage:[UIImage imageNamed:@"圆形头像"] forState:UIControlStateNormal];
    right.titleLabel.font=[UIFont systemFontOfSize:15];
    [right setTitleEdgeInsets:UIEdgeInsetsMake(0, 20, 0, 0)];
    [right setTitle:@"好友" forState:UIControlStateNormal];
    [right setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(handelRight) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:right];
    
}
- (void)handelRight
{
    MyFriendViewController *myfriend=[[MyFriendViewController alloc]initWithNibName:@"MyFriendViewController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:myfriend animated:YES];
}
/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
